from frappe.contacts.doctype.address import address
import frappe

# 地址下拉选择 显示详细地址以及电话信息，方便用户选择具体的地址

@frappe.whitelist()
@frappe.validate_and_sanitize_search_inputs
def custom_address_query(doctype, txt, searchfield, start, page_len, filters):
	from frappe.desk.reportview import get_match_cond

	doctype = "Address"
	link_doctype = filters.pop("link_doctype")
	link_name = filters.pop("link_name")

	condition = ""
	meta = frappe.get_meta(doctype)
	for fieldname, value in filters.items():
		if meta.get_field(fieldname) or fieldname in frappe.db.DEFAULT_COLUMNS:
			condition += f" and {fieldname}={frappe.db.escape(value)}"

	searchfields = meta.get_search_fields()

	if searchfield and (meta.get_field(searchfield) or searchfield in frappe.db.DEFAULT_COLUMNS):
		searchfields.append(searchfield)

	search_condition = ""
	for field in searchfields:
		if search_condition == "":
			search_condition += f"`tabAddress`.`{field}` like %(txt)s"
		else:
			search_condition += f" or `tabAddress`.`{field}` like %(txt)s"

	return frappe.db.sql(
		"""select
			`tabAddress`.name, `tabAddress`.city, `tabAddress`.country,`tabAddress`.address_line1,`tabAddress`.phone
		from
			`tabAddress`
		join `tabDynamic Link`
			on (`tabDynamic Link`.parent = `tabAddress`.name and `tabDynamic Link`.parenttype = 'Address')
		where
			`tabDynamic Link`.link_doctype = %(link_doctype)s and
			`tabDynamic Link`.link_name = %(link_name)s and
			ifnull(`tabAddress`.disabled, 0) = 0 and
			({search_condition})
			{mcond} {condition}
		order by
			case
				when locate(%(_txt)s, `tabAddress`.name) != 0
				then locate(%(_txt)s, `tabAddress`.name)
				else 99999
			end,
			`tabAddress`.idx desc, `tabAddress`.name
		limit %(page_len)s offset %(start)s""".format(
			mcond=get_match_cond(doctype),
			search_condition=search_condition,
			condition=condition or "",
		),
		{
			"txt": "%" + txt + "%",
			"_txt": txt.replace("%", ""),
			"start": start,
			"page_len": page_len,
			"link_name": link_name,
			"link_doctype": link_doctype,
		},
	)

address.address_query=custom_address_query
